package com.db.httpserver;


import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.*;
import org.junit.Test;

	public class NetTest {

		private static final int NTHREDS = 100;
		private static final int NREQUESTS = 1000;
		private static final int PORT = 8081;

		@Test
		public void testHttpServerOnLoad() throws InterruptedException, IOException {
			
			// given
			Server server = new Server(PORT);
	        Executors.newSingleThreadExecutor().execute( server );
	        
	        long startTime = System.nanoTime();
	        
	        // when
	        ExecutorService clientExecutor = Executors.newFixedThreadPool(NTHREDS); 
			for (int i = 0; i < NREQUESTS; i++) {
				clientExecutor.execute( new NetClient(PORT) );
			}

			clientExecutor.shutdown();
			clientExecutor.awaitTermination(1000, TimeUnit.SECONDS);
			
			// then
			long elapsed = System.nanoTime() - startTime;
			System.out.println("elapsed time : " + elapsed / 1000000 + "ms");
			assertEquals(NREQUESTS, WorkerThread.getSuccesfulConnectionsCounter().intValue());
			System.out.println("all requests succesful");
		}

	}
